import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  forwardRef,
  ChangeDetectorRef,
  Input,
  AfterViewInit,
  ViewChild,
  ElementRef,
  OnDestroy,
} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { Subject, fromEvent } from 'rxjs';
import { takeUntil, auditTime } from 'rxjs/operators';

/**
 * 查看用户角色组件
 */
@Component({
  selector: 'role-view-group',
  templateUrl: './role-view-group.component.html',
  styleUrls: ['./role-view-group.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RoleViewComponent),
      multi: true,
    },
  ],
})
export class RoleViewComponent implements AfterViewInit, OnInit, OnDestroy {
  @ViewChild('roleSpan', { static: true })
  roleSpan: ElementRef;
  @Input() roleList = [];
  private _curEl: HTMLElement = null;
  private unsubscribe$ = new Subject<void>();

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    this.cdr.detectChanges();
  }

  ngAfterViewInit(): void {
    const { roleSpan, unsubscribe$ } = this;
    let { _curEl } = this;

    const parentEl = roleSpan.nativeElement as HTMLElement;
    fromEvent(parentEl, 'mouseover')
      .pipe(
        takeUntil(unsubscribe$),
        auditTime(250),
      )
      .subscribe((e: MouseEvent) => {
        const target = (e.target as HTMLElement).closest('.iconfont') as HTMLElement;
        if (!target || !parentEl.contains(target)) {
          return;
        }
        target.classList.add('active');
        _curEl = target;
      });
    fromEvent(parentEl, 'mouseleave')
      .pipe(
        takeUntil(unsubscribe$),
        auditTime(250),
      )
      .subscribe((e: MouseEvent) => {
        if (_curEl) {
          _curEl.classList.remove('active');
        }
      });
    _curEl = parentEl.querySelector('.active') || null;
  }

  ngOnDestroy(): void {
    const { unsubscribe$ } = this;
    unsubscribe$.next();
    unsubscribe$.complete();
  }
}
